﻿using Abp.Domain.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Yozeev.BusinessLogic;
using Yozeev.BusinessLogic.Stats.Dtos;

namespace Yozeev.Controllers.Stats.Oper
{
    public class YearlyTimeSpan: ITimeSpan
    {
        private readonly IRepository<Activity, Guid> _activityRep;

        public YearlyTimeSpan(IRepository<Activity, Guid> activityRep)
        {
            _activityRep = activityRep;
        }

        public IQueryable<Activity> GetActivities(string date)
        {
            if (!String.IsNullOrEmpty(date))
            {
                //传了日期，根据日期查询
                DateTime orignDate = DateTime.Parse(date);
                DateTime startDateTime = new DateTime(orignDate.Year, 1, 1); // at 00:00:00
                DateTime endDateTime = orignDate.AddYears(1).AddTicks(-1); // at 23:59:59
                return _activityRep.GetAll().Where(a => a.CreationTime >= startDateTime && a.CreationTime <= endDateTime);
            }
            else
            {
                //日期为空，默认查询当zhou
                DateTime today = DateTime.Now;
                DateTime startDateTime = new DateTime(today.Year, 1, 1);//Today at 00:00:00
                DateTime endDateTime = today.AddYears(1).AddTicks(-1); //Today at 23:59:59
                return _activityRep.GetAll().Where(a => a.CreationTime >= startDateTime && a.CreationTime <= endDateTime);
            }
        }

        public IQueryable<RevenueQueryDto> Query(IQueryable<Activity> activities)
        {
            return from activity in activities
                   group activity by activity.CreationTime.Month into g
                   select new RevenueQueryDto
                   {
                       Hours = g.Key,
                       TotalAmount = g.Sum(a => a.TotalAmount),
                       TotalQuantity = (int)g.Sum(a => a.TotalQuantity)
                   };
        }
    }
}
